<template>
	<view class="content">
		<u-loading-page :loading="loading" bg-color="#e8e8e8" loading-text="loading..."></u-loading-page>
		<view class="host" style="padding-top: 15px;">
			<view class="host_body" v-for="(item,index) in hostList" :key="index">
				<view class="imageing" v-if="item.imgPath.split(',')[0]" @click="previewImage(index)">
					<img style="width: 345rpx;" mode="widthFix" :src="baseUrl+item.imgPath.split(',')[0]">
				</view>
				<view class="host_darkness">
					<u-row class="ty" justify="space-between">
						<u-col span="5" class="yui">
							<p class="yui">{{item.name}}</p>
						</u-col>
						<u-col span="6">
							<u-row justify="start">
								<u-col span="4">
									<view class="animated like" hover-class="heartBeat">
										<image class="like" @click="toggleLike(index)"
											:src="item.isLiked ? '../../static/icon/点赞.png' : '../../static/icon/未点赞.png'"
											style="width: 40rpx; height: 40rpx;"></image>
									</view>
								</u-col>
								<u-col span="4">
									<view class="animated like" hover-class="heartBeat">
										<image class="like" @click="toggleCollection(index)"
											:src="item.isCollection ? '../../static/icon/收藏2.png' : '../../static/icon/收藏.png'"
											style="width: 40rpx; height: 40rpx;"></image>
									</view>
								</u-col>
								<u-col span="4">
									<view class="more-button" @click="goToPage(item)"> 更多 </view>
								</u-col>
							</u-row>
						</u-col>
					</u-row>
				</view>
			</view>
		</view>
		<!-- <tab-bar :current="1"></tab-bar> -->
		<u-toast ref="uToast" />
		<!-- 弹出框 -->
		<view>
			<u-popup :show="show" mode="bottom" @close="close">
				<view class="LoginAlert">
					<p class="AlertText">你未登录，请先登录</p>
					<view class="AlertButton">
						<u-button type="success" text="登录" @click="getEquipment()"></u-button>
					</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>
<script>
	import request from '@/util/request'
	export default {
		onLoad() {
			this.loading = true
			// 获取设备信息
			const systemInfo = uni.getSystemInfoSync();
			let deviceId = systemInfo.deviceId;
			this.deviceId = parseInt(deviceId);
			this.login()
			this.IsLogin();
		},
		onShow() {
			this.selectImgByTypeId()
		},
		data() {
			return {
				isLogin: false,
				show: false,
				deviceId: 0,
				baseUrl: 'https://absolutuniq.com:8088',
				loading: false,
				isLiked: false, // 是否已点赞
				isCollection: false, //是否已收藏
				status: 'loadmore',
				hostList: [],
			}
		},
		onReachBottom() {
			this.loading = true
			setTimeout(() => {
				// 这里放置你想要在等待5秒后执行的代码
				this.loading = false
			}, 1000);
			//数据触底以后，加载新的数据（就是加载新一页的数据）
		},
		computed: {
			divStyle() {
				return {
					color: 'green',
					border: '1px solid red'
				};
			},
		},
		methods: {
			//判断是否登录
			IsLogin() {
				const isLogin = uni.getStorageSync('isLogin');
				this.isLogin = isLogin;
			},
			//取消弹出框
			close() {
				this.show = false

			},
			login() {
				wx.login({
					success: res => {
						const code = res.code; //
					}
				})
			},
			//登录
			getEquipment() {
				wx.getUserProfile({
					desc: '获取你的头像和昵称',
					success: (res) => {
						request({
							url: '/users/login',
							method: 'post',
							data: this.deviceId
						}).then(res => {
			
						}).catch(err => {
							
						});
						uni.setStorage({
							key: 'isLogin',
							data: true
						})
						uni.setStorage({
							key: 'isUser',
							data: res.userInfo
						})
						uni.reLaunch({
							url: "/pages/my/index"
						})
					},
					fail: (err) => {
					
					}
				});
			},
			showToast() {
				this.$refs.uToast.show({
					title: '加载数据',
					message: "加载数据",
					type: 'success',
				})
			},
			// 定义跳转方法
			goToPage(item) {
				// 使用 uni.navigateTo 进行页面跳转
				uni.reLaunch({
					url: `/pages/home/index?id=${item.imgTypeId}`
				});
			},
			toggleLike(index) {
				const isLogin = this.isLogin;
				if (isLogin) {
					// 切换点赞状态
					this.hostList[index].isLiked = !this.hostList[index].isLiked;
					// 准备发送到后端的数据
					const imgId = this.hostList[index].id; // 假设每个图像对象有一个 id
					const isLiked = this.hostList[index].isLiked;
					
					// 发送请求到后端
					request({
						url: '/favorites/favorites/toggleLike', // 假设这是处理点赞的后端 API 路径
						method: 'POST',
						data: {
							userId: this.deviceId, // 用户 ID
							imgManageId: imgId, // 图像 ID
							liked: isLiked // 当前的点赞状态
						}
					}).then(res => {
					
					}).catch(err => {
					
					});
				} else {
					this.show = true
				}
			},
			// 收藏方法
			toggleCollection(index) {
				const isLogin = this.isLogin;
				if (isLogin) {
					//切换收藏状态
					this.hostList[index].isCollection = !this.hostList[index].isCollection;
					// 准备发送到后端的数据
					const imgId = this.hostList[index].id; // 假设每个图像对象有一个 id
					const isCollection = this.hostList[index].isCollection;
					
					// 发送请求到后端
					request({
						url: '/favorites/favorites/toggleCollection', // 假设这是处理点赞的后端 API 路径
						method: 'POST',
						data: {
							userId: this.deviceId, // 用户 ID
							imgManageId: imgId, // 图像 ID
							col: isCollection // 当前的收藏状态
						}
					}).then(res => {
					
					}).catch(err => {
					
					});
				} else {
					this.show = true
				}
			},
			selectImgByTypeId() {
				this.loading = true; // 开始加载状态
				// 获取图片
				const getImagesRequest = request({
					url: '/imgmanage/imgmanage/selectImgNewestByTypeId',
					method: 'get'
				});
				// 获取用户点赞图片
				const getLikesRequest = request({
					url: '/favorites/favorites/getUserImageLike?id=' + this.deviceId,
					method: 'get'
				});
				// 获取用户收藏图片
				const getCollectionsRequest = request({
					url: '/favorites/favorites/getUserImageCollection?id=' + this.deviceId,
					method: 'get'
				});
				Promise.all([getImagesRequest, getLikesRequest, getCollectionsRequest]).then(responses => {
					const [imageResponse, likeResponse, collectionResponse] = responses;
					// 处理图片数据
					this.hostList = imageResponse.data.map(item => ({
						...item,
						isCollection: false, // 初始状态为未收藏
						isLiked: false, // 初始状态为未点赞
						likeCount: 0 // 添加点赞数量字段
					}));
					if (this.isLogin) {
						// 处理点赞数据
						const likedIds = new Set(likeResponse.data);
						this.hostList = this.hostList.map(item => ({
							...item,
							isLiked: likedIds.has(item.id) // 更新点赞状态
						}));
						// 处理收藏数据
						const collectedIds = new Set(collectionResponse.data);
						this.hostList = this.hostList.map(item => ({
							...item,
							isCollection: collectedIds.has(item.id) // 更新收藏状态
						}));
					}
					this.loading = false; // 加载结束
				}).catch(error => {
					this.loading = false; // 加载结束
				});
			},
			previewImage(index) {
				const imgUrls = this.hostList[index].imgPath.split(",");
				if (imgUrls.length > 0) {
					const newurls = imgUrls.map(item => {
						return item = this.baseUrl + item;
					});
					// 调用预览图片API
					uni.previewImage({
						current: 0, // 当前显示图片索引
						urls: newurls, // 需要预览的图片URL列表
					});
				}
			}
		}
	}
</script>
<style lang="scss">
	.like {
		color: #ffe833;
		filter: none;
		will-change: font-size;
		-webkit-animation: heart 1s cubic-bezier(0.17，8.89，8.32，1.49);
		animation: heart 1s cubic-bezier(0.17，0.89，8.32，1.49);
		width: 40rpx;
		height: 40rpx;
	}

	.noLike {
		width: 40rpx;
		height: 40rpx;
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.host {
		margin-top: 40rpx;
		margin: 0 auto;
		padding: 0 20rpx;
		column-count: 2;
		column-gap: 20rpx;
	}

	.host_body {
		width: 345rpx;
		border-radius: 20rpx;
		box-sizing: border-box;
		overflow: hidden;
		background-color: #fff;
		break-inside: avoid;
		/*避免在元素内部插入分页符*/
		box-sizing: border-box;
		/* 	margin-top: rpx; */
		margin-bottom: 20rpx;
		box-shadow: 0px 0px 28rpx 1rpx rgba(78, 101, 153, 0.14);
	}

	.imageing {
		width: 345rpx;
		height: auto;
	}

	.types {
		width: 95%;
		margin: 0 auto;
		height: 70rpx;
	}

	.types_son {
		width: 80%;
		margin: 0 auto;
		height: 70rpx;
	}

	.imageing_img {
		width: 345rpx;
		height: auto;
	}

	.host_darkness {
		padding-left: 16rpx;
		font-size: 24rpx;
		margin-top: 15rpx;
		padding-bottom: 22rpx;
	}

	.darkness_silence {
		font-weight: 800;
		margin-top: 12rpx;
		font-size: 27rpx;
		margin-left: 10rpx;
	}

	.yui {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		margin-top: 5px;
	}

	/* 弹出框 */
	.LoginAlert {
		width: 95%;
		height: 200rpx;
		text-align: center;
		font-size: 30rpx;
	}

	/* 弹出框按钮 */
	.AlertButton {
		width: 80%;
		margin: auto;
	}

	/* 弹出框文字 */
	.AlertText {
		margin-top: 20rpx;
		margin-bottom: 20rpx;
	}
</style>